package org.jmc.refmanager.web.wicket.page.panel.signin;

import org.apache.wicket.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.value.ValueMap;
import org.jmc.refmanager.domain.model.User;
import org.jmc.refmanager.domain.service.UserManager;
import org.jmc.refmanager.web.wicket.page.HomePage;
import org.jmc.refmanager.web.wicket.page.SignInPage;
import org.springframework.security.authentication.encoding.PasswordEncoder;

/**
 */
public class ChangePasswordPage extends WebPage {
	@SpringBean(name="userManager")
	private UserManager userManager;

	@SpringBean(name = "passwordEncoder")
	private PasswordEncoder passwordEncoder;

	/**
	 * Field for password.
	 */
	private PasswordTextField password;

	/**
	 * Field for user name.
	 */
	private TextField<String> username;

	/**
	 * Field for new password.
	 */
	private PasswordTextField newPassword;

	/**
	 * Field for new password.
	 */
	private PasswordTextField confirmNewPassword;

	/**
	 * 
	 */
	public ChangePasswordPage() {
		super();

		// Create feedback panel and add to page
		final FeedbackPanel feedback = new FeedbackPanel("feedback");
		add(feedback);

		add(new ChangePasswordForm("changePwdForm"));
	}
	
	/**
	 * Sign in user if possible.
	 * 
	 * @param username
	 *            The username
	 * @param password
	 *            The password
	 * @return True if signin was successful
	 */
	public boolean signIn(String username, String password)	{
		return AuthenticatedWebSession.get().signIn(username, password);
	}

	/**
	 * 
	 *
	 */
	final class ChangePasswordForm extends Form<Void> {
		private static final long serialVersionUID = 1L;

		private final ValueMap properties = new ValueMap();

		public ChangePasswordForm(String id) {
			super(id);

			add(username = new RequiredTextField<String>("username",
					new PropertyModel<String>(properties, "username")));
			add(password = new PasswordTextField("password",
					new PropertyModel<String>(properties, "password")));

			username.setType(String.class);
			password.setType(String.class);

			add(confirmNewPassword = new PasswordTextField("confirmNewPassword",
					new PropertyModel<String>(properties, "confirmNewPassword")));
			add(newPassword = new PasswordTextField("newPassword",
					new PropertyModel<String>(properties, "newPassword")));

			confirmNewPassword.setType(String.class);
			newPassword.setType(String.class);

	        add(new Button("btnCancel") {
	        	private static final long serialVersionUID = 1L;
	        	@Override
	        	public void onSubmit() {
                    setResponsePage(SignInPage.class);
                }
	        }.setDefaultFormProcessing(false));

	        add(new Button("btnValidate") {
				private static final long serialVersionUID = 1L;
	        	public void onSubmit() {
	        		// Verification du mot de passe
	    			if (signIn(getUsername(), getPassword())) {
	    				User user = userManager.getByMatricule(getUsername());
	    				String encodedNewPassword = passwordEncoder.encodePassword(getNewPassword(), null);
	    				String encodedPassword = passwordEncoder.encodePassword(getPassword(), null);
		        		// Appel au changement de mot de passe
	    				userManager.changePassword(user, encodedPassword, encodedNewPassword);
	    				// Redirection vers la page d'accueuil
	                    setResponsePage(HomePage.class);
	    			} else {
	    				error("Impossible d'identifier la matricule");
	    			}
                }
	        });
	        
	        this.add(new EqualPasswordInputValidator(newPassword, confirmNewPassword));
		}
		
		/* (non-Javadoc)
		 * @see org.apache.wicket.markup.html.form.Form#onSubmit()
		 */
		@Override
		protected void onSubmit() {
			super.onSubmit();
		}
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return this.password.getInput();
	}

	/**
	 * @return the username
	 */
	public String getUsername() {
		return this.username.getDefaultModelObjectAsString();
	}

	/**
	 * @return the newPassword
	 */
	public String getNewPassword() {
		return this.newPassword.getDefaultModelObjectAsString();
	}


	/**
	 * @return the confirmNewPassword
	 */
	public String getConfirmNewPassword() {
		return this.confirmNewPassword.getDefaultModelObjectAsString();
	}

}

